<?php

namespace common\models;

use Yii;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\Category;
use common\models\Brand;
use common\models\ProductCategory;

/**
 * This is the model class for table "product".
 *
 * @property integer $id
 * @property string $name
 * @property string $title
 * @property string $keywords
 * @property string $img_url 
 * @property string $des
 * @property string $market_price
 * @property string $product_price
 * @property string $promotion_price
 * @property string $price_unit
 * @property integer $spec
 * @property string $weight
 * @property integer $weight_unit
 * @property integer $brand_id
 * @property integer $company_id 
 * @property integer $stock
 * @property string $serial_number
 * @property integer $full_cut_shipping_free
 * @property integer $supply
 * @property integer $send_sample
 * @property integer $is_show
 * @property integer $sort_numer
 * @property integer $hot_sort 
 * @property string $create_time
 * @property string $update_time
 */
class Product extends \yii\db\ActiveRecord
{

    public $suc_amount;
    public $category_name;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'product';
    }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name','title','product_price','brand_id','price_unit','category_name'], 'required'],
            [['des'], 'string'],
            //[['name'], 'unique'],
            [['market_price', 'product_price', 'promotion_price', 'weight'], 'number'],
            [['weight_unit', 'brand_id','company_id', 'stock', 'serial_number', 'full_cut_shipping_free', 'supply','send_sample', 'is_show', 'sort_numer','hot_sort'], 'integer'],
            [['create_time', 'update_time','spec'], 'safe'],
            [['name'], 'string', 'max' => 50],
            [['keywords','img_url'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '名称',
            'title' => '商品标题',
            'keywords' => '关键词',
            'img_url' => '商品封面图', 
            'des' => '描述',
            'market_price' => '市场价',
            'product_price' => '商品价',
            'promotion_price' => '促销价',
            'price_unit' => '价格单位',
            'spec' => '规格',    // 1个，2斤，3公斤 ，4吨',
            'weight' => '重量',
            'weight_unit' => '重量规格',//1千克2克',
            'brand_name' => '品牌名',
            'brand_id' => '品牌名称',
            'company_id' => '供应商',
            'company_name' => '供应商',
            'stock' => '库存',
            'serial_number' => '序列号',
            'full_cut_shipping_free' => '参加满多少元减快递费',//1不参加2参加',
            'supply' => '供应方式',//1（3天内发货），2（1星期内发货） 3（其它）',
            'is_show' => '显示否',//1显示2隐藏',
            'send_sample' => '寄样品',//1不允许 2允许,
            'sort_numer' => '排序',
            'hot_sort' => '首页热销排序',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'category_name' => '分类名',
        ];
    }

    public static function itemAlias ($type, $code = NULL)
    {
        $_items = [
            'send_sample' => [
                //''  =>'显示状态',
                '1' => "不允许",              
                '2' => "允许",              
            ],
            'supply' => [
                //''  =>'显示状态',
                '1' => "3天内发货",              
                '2' => "1星期内发货",
                '3' => "其他",
            ],
            'full_cut_shipping_free' => [
                //''  =>'显示状态',
                '1' => "不参加",              
                '2' => "参加",              
            ],
            'weight_unit' => [
                //''  =>'显示状态',
                '1' => "千克",              
                '2' => "克",              
            ],
            /*'price_unit' => [
                ''  =>'全部',
                '1' => "元/千克",              
                '2' => "元/吨",
            ],*/
            'is_show' => [
                //''  =>'显示状态',
                '1' => "显示",              
                '2' => "隐藏",              
            ],
        ];
        
       
        if (isset($code))
            return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
        else
            return isset($_items[$type]) ? $_items[$type] : false;
    }


    /**
     * model->brand
     * @return [type] [description]
     */
    /*public function getProductCategory()
    {
        return $this->hasOne(ProductCategory::className(), ['id' => 'product_id']);
    } 
*/
    public function getCompany()
    {
        return $this->hasOne(Company::className(), ['id' => 'company_id']);
    }
    public function getBrand()
    {
        return $this->hasOne(Brand::className(), ['id' => 'brand_id']);
    }  
   
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id'])
                ->viaTable('product_category', ['product_id' => 'id'])->groupBy('id');
    }

    public static function listCompany($id = 0){

        $li = [];
        if($id){
            $li[''] = '';
        }
        $list = Company::find()
            ->select(['id','company_name'])
            ->asArray()
            ->all();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $li[$v['id']] = $v['company_name'];
            }
            //var_dump($li);exit;
            return $li;
        }
        
        return $li;
    }

    public static function listBrand(){

        $list = Brand::find()
            ->select(['id','name'])
            ->asArray()
            ->all();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $li[$v['id']] = $v['name'];
            }
            //var_dump($li);exit;
            return $li;
        }
        
        return [];
    } 

    public static function listCategory(){

        $list = Category::find()
            ->select(['id','name','level','parent_id'])
            ->where(['is_show'=>1])
            ->asArray()
            ->orderBy('level,parent_id,sort_number,id')
            ->all();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $li[$v['id']] = $v['name'];
            }
            //var_dump($list);exit;
            return $li;
        }
        
        return [];
    } 

    public static function listCate(){

        $list = ProductCategory::find()
            ->select(['category.id','category.name'])
            ->leftJoin('category','product_category.category_id = category.id')
            ->asArray()
            ->all();
        $li = [];    
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                if($v['name']){
                    $li[$v['id']] = $v['name'];
                }
            }
            //var_dump($li);exit;
            return $li;//ArrayHelper::map($li,'id','name');
        }
        
        return $li;
    } 

    /**
     * 分类名称
     * @param [type] $id [description]
     */
    public  static function ProductCategoryname($id)
    {
        $arr = [];
        $id = intval($id);
        if(!$id) {return $arr;}
        $db = Yii::$app->db;
        $sql = "SELECT c.id,c.name FROM product_category p LEFT JOIN category  c
            ON  p.category_id=c.id 
            WHERE  product_id=$id ORDER BY c.parent_id ASC,c.id ASC";
        $cate_list = $db->createCommand($sql)->queryAll();
        if(!empty($cate_list)) {
            $arr = ArrayHelper::map($cate_list, 'id', 'name');
        }
        return $arr;
    }      


    /*
    * 保存前执行的操作
    */
    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            //是否是新添加
            if($this->isNewRecord) {
                /*if(!$this->is_show) $this->is_show = 1;*/
                //if(!$this->spec) $this->spec = 99;
                /*if(!$this->weight_unit) $this->weight_unit = 1;
                if(!$this->full_cut_shipping_free) $this->full_cut_shipping_free = 1;
                if(!$this->supply) $this->supply = 1;
                if(!$this->send_sample) $this->send_sample = 1;
                if(!$this->company_id) $this->company_id =0;*/
                if(!$this->promotion_price) $this->promotion_price =0;
                if(!$this->market_price) $this->market_price =0;
                if(!$this->weight) $this->weight =0;
                if(!$this->stock) $this->stock = 99;
                if(!$this->sort_numer) $this->sort_numer =999;
                if(!$this->serial_number) $this->serial_number =0;

                
                $this->create_time = date("Y-m-d H:i:s", time());
                $this->update_time = date("Y-m-d H:i:s", time());
            }else{
                $this->update_time = date("Y-m-d H:i:s", time());
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * @author wgx 2016-07-22 11:32:52
     * @desc 验证商品库存是否足够
     * @param int $user_id 用户id
     */
    public static function isEnough(){

    }
}
